package com.briup.common.jwt;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.briup.common.exception.CustomerException;
import com.briup.common.web.MessageStatus;
import com.briup.common.web.SecurityUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wood
 * @date 2021/4/9 - 23:53
 */
public class JwtInterceptor implements HandlerInterceptor {

    private RestTemplate restTemplate;

    private String remoteAuthCheckUrl;

    public JwtInterceptor(RestTemplate restTemplate,String remoteAuthCheckUrl){
        this.restTemplate = restTemplate;
        this.remoteAuthCheckUrl = remoteAuthCheckUrl;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }

        // 从 http 请求头中取出 Authorization 字段的值，也是jwt的token值
        String token = httpServletRequest.getHeader("Authorization");

        if (token == null) {
            throw new CustomerException(MessageStatus.USER_TOKEN_NOT_EXIST);
        }

        // TODO: 模拟测试，真正上线后删除
        if("briup".equals(token)){
            Map<String, Object> map = new HashMap<>();
            map.put("id","1");
            map.put("username","tom");
            map.put("realname","张三丰");
            map.put("telephone","13812811111");
            saveInfo(httpServletRequest,map);
            return true;
        }

        // 验证 token
        try {
//            JwtUtil.checkSign(token);
//             restTemplate 发送请求给认证服务器来验证token
            checkToken(token);
        } catch (JWTVerificationException e) {
            throw new CustomerException(MessageStatus.USER_TOKEN_INVALID);
        }

        saveInfo(httpServletRequest,JwtUtil.getInfo(token));

        // 验证通过后，这里测试取出JWT中存放的数据
        // 获取 token 中的 userId
//        String userId = JwtUtil.getUserId(token);
//        System.out.println("id:" + userId);

        // 获取 token 中的 其他数据
//        Map<String, Object> info = JwtUtil.getInfo(token);
//        info.forEach((k,v)->System.out.println(k+":"+v));


        return true;
    }

    private boolean checkToken(String token){

        // 请求头参数
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        header.set("Authorization", token);
        // 请求体参数
        String jsonStr = "{}";

        // 请求头和请求体组合在一起
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonStr, header);

        // 给指定url地址，发起post请求
        String result = this.postForObject(remoteAuthCheckUrl,requestEntity);

        return (Boolean) JSON.parseObject(result).get("data");
    }

    private String postForObject(String url ,HttpEntity<?> requestEntity){
        String jsonStr = null;
        try {
            jsonStr = restTemplate.postForObject(url, requestEntity, String.class);
        } catch (Exception e) {
            throw new CustomerException(MessageStatus.USER_TOKEN_CHECK_FAIL);
        }
        return jsonStr;
    }

    private void saveInfo(HttpServletRequest httpServletRequest,Map<String, Object> map){
        String method = httpServletRequest.getMethod();
        String requestURI = httpServletRequest.getRequestURI();

        String id = (String) map.get("id");
        String username = (String) map.get("username");
        String realname = (String) map.get("realname");
        String telephone = (String) map.get("telephone");

        SecurityUtil.setmethod(method);
        SecurityUtil.setRequestURI(requestURI);
        SecurityUtil.setUserId(id);
        SecurityUtil.setUsername(username);
        SecurityUtil.setRealname(realname);
        SecurityUtil.setTelephone(telephone);

    }

}
